/**
 * Copyright (C) Baidu Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rubik.context

import com.rubik.Rubik
import com.rubik.route.Queries
import com.rubik.route.Query
import com.rubik.route.ResultGroups
import com.rubik.router.annotations.RInvariant

/**
 * Aggregate router function and router event of Context.
 * The specific implementation will be automatically generated by rubik-kapt.
 *
 * @since: 1.0
 */
interface Aggregatable {
    /**
     * Will invoking when route to a RRouter function.
     */
    fun onRoute(path: String, queries: Queries, results: ResultGroups)
    /**
     * Will invoking when route to a REvent function.
     */
    fun onEvent(msg: String, queries: Queries)
}

abstract class AggregateFactory {
    abstract val URI: String
    open val DEPENDENCIES: List<String> = listOf()
    abstract val EVENT_MSGS: List<String>
    abstract val CREATOR: () -> Aggregatable

    @RInvariant
    fun register() {
        Rubik.registerAggregateFactory(this)
    }
}

fun Aggregatable.doEvent(msg: String, vararg args: Any) {
    onEvent(msg, Queries().apply {
        args.forEachIndexed { index, value ->
            add(Query("rubik_aggregate_live_arg${index}", value))
        }
    })
}